package ua.eug.airv1.controllers;

import com.badlogic.gdx.math.Vector2;

import ua.eug.airv1.map.Tile;
import ua.eug.airv1.map.TilePos;
import ua.eug.airv1.orders.EOrder;
import ua.eug.airv1.orders.WeaponOrder;
import ua.eug.airv1.utils.Config;
import ua.eug.airv1.utils.EDirection;
import ua.eug.airv1.weapon.IWeapon;
import ua.eug.airv1.weapon.ZWeapon;

public class OrderController implements IController {

	private WeaponOrder targetOrder;
	private IWeapon targetWeapon;
	private Vector2 delta = new Vector2();
	private TilePos cursor = new TilePos();
	private EDirection dir;
	private int orderStep;
	private float zoom = 1f;
	
	protected OrderController() {
		
	}
	
	private static class SingletonHolder {
        public static final OrderController HOLDER = new OrderController();
    }
	
	public static OrderController getInstance() {
        return SingletonHolder.HOLDER;
    }

	public void setZoom(float z) {
		zoom = z;
	}
	
	@Override
	public void touch(float x, float y, Tile t) {
		targetWeapon = t.getAirWeapon();
		if (targetWeapon.equals(ZWeapon.Nobody)) { // TODO ground
			targetWeapon = t.getGroundWeapon();
			if (targetWeapon.equals(ZWeapon.Nobody)) {
				return;
			}
		}
		
		targetOrder = targetWeapon.getOrder();
		targetOrder.setActive();
		cursor.set(t.pos);
		dir = targetWeapon.getDirection();
		delta.set(0, 0);
		orderStep = 0;
	}

	@Override
	public void pan(float deltaX, float deltaY, Tile tile) {
		if(orderStep >= targetWeapon.getNMoves()) {
			return;
		}
		delta.add(deltaX, deltaY);
		// check delta
		EOrder nextOrder = isNextTile();
		if(nextOrder != EOrder.NONE) {
			targetOrder.setStep(orderStep++, nextOrder);
			targetOrder.setStep(orderStep, EOrder.NONE);
			dir = dir.getNext(nextOrder);
		}
	}

	@Override
	public void endTouch() {
		if(orderStep >= targetWeapon.getNMoves()) {
			targetOrder.setOrderDone(true);
		} else {
			targetOrder.setOrderDone(false);
		}
	}
	
	// check tile location from shift
	private EOrder isNextTile() {
		EDirection d2 = EDirection.NEE;
		if (delta.len2() > Config.DeltaVectorSize*zoom) {
			
			float angle = delta.angle();
			delta.set(0, 0);
			
			if (angle<60) 
				d2 = EDirection.NEE;
			else if (angle<120) 
				d2 = EDirection.N;
			else if (angle<180) 
				d2 = EDirection.NWW;
			else if (angle<240) 
				d2 = EDirection.SWW;
			else if (angle<300) 
				d2 = EDirection.S;
			else
				d2 = EDirection.SEE;

			System.out.println("Order angle " + angle + " " + d2 + " " + dir);
			return dir.getTurn(d2);
		}
		return EOrder.NONE;
	}

}
